package com.example.wlzz.service.serviceImpl;

import com.example.wlzz.constant.RedisConstant;
import com.example.wlzz.entity.User_;
import com.example.wlzz.entity.UserInfo;
import com.example.wlzz.entity.admin.UserWithRole;
import com.example.wlzz.enums.ResultEnum;
import com.example.wlzz.form.RegisterForm;
import com.example.wlzz.form.UserForm;
import com.example.wlzz.repository.UserInfoRepository;
import com.example.wlzz.repository.UserRepository;
import com.example.wlzz.repository.UserWithRoleRepository;
import com.example.wlzz.service.UserService;
import com.example.wlzz.utils.CodeUtil;
import com.example.wlzz.utils.KeyUtil;
import com.example.wlzz.utils.MD5Util;
import com.example.wlzz.utils.ResultVOUtil;
import com.example.wlzz.vo.LoginUserInfoVO;
import com.example.wlzz.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class UserServiceImpl implements UserService{
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private UserWithRoleRepository userWithRoleRepository;
    @Override
    public User_ findByPhone(String phone) {
        return userRepository.findByPhone(phone);
    }
    @Override
    @Transactional
    public ResultVO register(UserForm userForm) {  //注册
             //再二次盐值加密
            String salt = CodeUtil.getCode();
            User_ isUser = userRepository.findByPhone(userForm.getPhone());
            if(isUser!=null){  //手机号已被注册
                return ResultVOUtil.error(ResultEnum.PHONE_REPEAT.getCode(),ResultEnum.PHONE_REPEAT.getMessage());
            }
            User_ user = new User_();
            user.setPhone(userForm.getPhone());
            user.setPassword(MD5Util.EncoderByMd5(userForm.getPassword() + salt));
            user.setSalt(salt);
            user.setCreateTime(new Date());
            User_ user1 = userRepository.save(user);
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(user1.getUserId());
            userInfo.setNickName(KeyUtil.genUniqueKey());
            userInfo.setRollNumber("500");
            userInfo.setImgUrl("http://39.108.97.134:8886/wlzz/images/logo.jpg");
            UserInfo userInfo1 =  userInfoRepository.save(userInfo);

            //分配权限
            UserWithRole userWithRole = new UserWithRole();
            userWithRole.setUserid(user1.getUserId());
            userWithRole.setCreateTime(user1.getCreateTime());
            userWithRole.setStatus(0);
            userWithRole.setRoleId(1);  //默认普通用户权限
           userWithRoleRepository.save(userWithRole);
            return ResultVOUtil.success(userInfo1);
    }
    @Override
    public ResultVO login(RegisterForm userForm) {
        String cookieToken = UUID.randomUUID().toString(); //token值
        Integer expire = RedisConstant.EXPIRE;  //验证码时长
             User_ isUser = userRepository.findByPhone(userForm.getPhone()); //从数据库获取用户信息
            if(isUser==null){  //判断用户存不存在
                return ResultVOUtil.error(ResultEnum.PHONE_NOT_EXIST.getCode(),ResultEnum.PHONE_NOT_EXIST.getMessage());
            }
            if(isUser.getPassword().equals(MD5Util.EncoderByMd5(userForm.getPassword()+isUser.getSalt()))){  //用户账号密码匹配
                log.info("用户账户密码匹配成功,phone={}"+isUser.getPhone());
                //设置token至redis
                redisTemplate.opsForValue().set(String.format(RedisConstant.LOGIN_SUCCESS_TOKEN, cookieToken), userForm.getPhone(), expire, TimeUnit.SECONDS);
                UserInfo userInfo =  userInfoRepository.findByUserId(isUser.getUserId());
                LoginUserInfoVO loginUserInfoVO = new LoginUserInfoVO();
                if(userInfo!=null) {   //登陆成功应该返回的用户信息
                    BeanUtils.copyProperties(userInfo, loginUserInfoVO);
                }
                else{
                    return ResultVOUtil.error(ResultEnum.USERINFO_NO_EXIST.getCode(),ResultEnum.USERINFO_NO_EXIST.getMessage());
                }
                loginUserInfoVO.setToken(cookieToken);
                if(userInfo.getBirth()!=null){
                    System.out.println("时间不为空");
                    System.out.println("时间戳："+userInfo.getBirth().getTime());
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    loginUserInfoVO.setBirth(simpleDateFormat.format(userInfo.getBirth()));
                }
                return ResultVOUtil.success(loginUserInfoVO);
            }else{
                log.error("用户账户密码匹配失败,phone={}",userForm.getPhone());
                return ResultVOUtil.error(ResultEnum.LOGIN_ERROR.getCode(),ResultEnum.LOGIN_ERROR.getMessage());
        }
    }
    @Override
    public User_ findByUserId(Integer userId) {
        return userRepository.findByUserId(userId);
    }

    @Override
    public User_ findByPhoneAndPassword(String phone, String password) {
        return userRepository.findByPhoneAndPassword(phone,password);
    }

    @Override
    public User_ save(User_ user) {
        return userRepository.save(user);
    }
}
